﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//仓库管理,管理所有物品信息
public class InventoryManager : MonoBehaviour
{
    //单利
    public static InventoryManager Instance { get; private set; }
    //字典管理所有物品信息
    private Dictionary<ItemType, ItemData> itemDataDict = new Dictionary<ItemType, ItemData>();
    [HideInInspector]
    //仓库
    public InventoryData backpack;
    [HideInInspector]
    //状态栏
    public InventoryData toolbarData;

    private void Awake()
    {
        Instance = this;
        Init();
    }

    //初始化字典
    private void Init()
    {
        //找到物品放入数组
        ItemData[] itemDataArray = Resources.LoadAll<ItemData>("Data");
        //遍历数组
        foreach (ItemData data in itemDataArray)
        {
            itemDataDict.Add(data.type, data);
        }

        //给背包赋值
        backpack = Resources.Load<InventoryData>("Data/Backpack");
        //状态栏赋值
        toolbarData = Resources.Load<InventoryData>("Data/Toolbar");
    }

    //通关type得到对应的物品信息
    private ItemData GetItemData(ItemType type)
    {
        ItemData data;
        bool isSuccess = itemDataDict.TryGetValue(type, out data);
        if (isSuccess)
        {
            return data;
        }
        else
        {
            return null;
        }
    }

    //往仓库存储物品(拾起物品)
    public void AddToBackpack(ItemType type)
    {
        ItemData item = GetItemData(type);
        //如果为空
        if (item == null) return;

        foreach (SlotData slotData in backpack.slotList)
        {
            if (slotData.item == item && slotData.CanAddItem())
            {
                //当前格子的物品与拾取的物品类型相同
                slotData.Add();
                return;
            }
        }
        //找空格子
        foreach (SlotData slotData in backpack.slotList)
        {
            if (slotData.count == 0)
            {
                slotData.AddItem(item);
                return;
            }
        }

        //背包满了
        Debug.LogWarning("无法放入仓库，你的背包" + backpack + "已满。");
    }
}

